package com.tc.workflow;


import com.alibaba.fastjson.JSON;
import com.vip.vpal.workflow.WorkflowEngine;
import com.vip.vpal.workflow.entity.FormHeader;
import com.vip.vpal.workflow.entity.WorkflowFormItem;
import com.vip.vpal.workflow.manager.PageFormManager;
import com.vip.vpal.workflow.model.PageForm;
import org.team4u.sql.builder.util.SqlBuilders;

import java.util.Date;

public class SimplePageFormManager<H extends FormHeader, B> extends PageFormManager<H, B> {

    public SimplePageFormManager(WorkflowEngine workflowEngine) {
        super(workflowEngine);
    }

    @Override
    protected void fillBody(PageForm<H, B> form) {
        WorkflowFormItem item = dao.queryForObject(SqlBuilders.select(WorkflowFormItem.class)
                .where("formId", "=", form.getHeader().getId()));
        if (item != null) {
            form.setBody(JSON.parseObject(item.getBody(), bodyClass));
        }
    }

    @Override
    protected void saveBody(PageForm<H, B> form) {
        if (form.getBody() == null) {
            return;
        }
        WorkflowFormItem item = new WorkflowFormItem()
                .setFormId(form.getHeader().getId())
                .setBody(JSON.toJSONString(form.getBody()));

        item.setUpdateTime(new Date());

        if (form.isNewForm()) {
            item.setCreateTime(new Date());
            dao.insert(item);
        } else {
            dao.execute(SqlBuilders.update(WorkflowFormItem.class)
                    .setValue("body", item.getBody())
                    .where("formId", "=", item.getFormId()).create());
        }
    }
}